package example.reducejoin;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TableReducer extends Reducer<Text, TableBean, TableBean, NullWritable> {

    static {
        System.out.println();
    }

    @Override
    protected void reduce(Text key, Iterable<TableBean> values, Reducer<Text, TableBean, TableBean, NullWritable>.Context context)
            throws IOException, InterruptedException {

        List<TableBean> orders = new ArrayList<>();
        TableBean pd = new TableBean();

        for (TableBean value : values) {
            if (value.getFlag().equals("order")) {
                try {
                    TableBean tmp = new TableBean();
                    BeanUtils.copyProperties(tmp, value);
                    orders.add(tmp);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else {
                try {
                    BeanUtils.copyProperties(pd, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        for (TableBean order : orders) {
            order.setPname(pd.getPname());
            context.write(order, NullWritable.get());
        }


    }

}
